You are on page 1of 5

Google Web Toolkit Tutorial - douglasjose.com http://douglasjose.com/tech/tutorials/gwt.

html

Google Web Toolkit Tutorial


July, 2006

Learn to write AJAX applications from Java classes, using the new development paradigm introduced by this new Google framework.

Recently, the 1.20 version of Google Web Toolkit (GWT) was released. This framework introduces a new AJAX application development paradigm. Is goal is to
hide from programmer the JavaScript code implementation, considering this job is repetitive, error-prone and full of tedious tasks, like browser incompatibility
handling.
GWT abstracts JavaScript using a Java class library, where a visual AJAX components (the widgets) library is available. These components are well known by
GMail and Google Maps users.
This tutorial presents how GWT changes the application development paradigm, and brings an implementation sample using the framework.

Java classes advantages

The main feature presented by GWT is the Java class usage to represent AJAX visual components. These classes are converted to JavaScript code by a
compiler, distributed inside GWT package.
The advantage of using Java code is that it enables the developer to use its preferred Java IDE, once GWT is environment-independent. And when using a Java
IDE, you benefit from Java language features, like compiler type checking and editor code completion.

Framework architecture

A model of GWT architecture is presented below.

The architecture is split in two big layers. The first one is the libraries layer. This layer has a visual components layer, which represents user interface
components, and a Java emulation library, that contains the implementation of some classes from java.lang and java.util packages. These two libraries compose
the basic infrastructure necessary to represent the AJAX components using Java code. The other layer contains two tools. The first is the Java to JavaScript
compiler, which is responsible by generate the JavaScript code which represents the visual components. The second tool is a local browser. This browser
prevents the developer from converting is Java into JavaScript code every time he wants to do a test. The local browser is able to render the library components
without code conversion.

Installation

The first step to use GWT is to download the package from framework site. It's currently available to Windows and Linux. In this tutorial we're going to present
configuration instructions to Windows, remembering that the procedures almost the same for Linux. This tutorial was built using GTW version 1.0.20. The
package is distributed in a zip file, and its size is 13.9 MB.
The installation is very simple: just unzip the distribution package in a local directory. In this directory will be created the GWT libraries and some project
configuration utilities.
This tutorial will be written using Eclipse WTP. This IDE was choose because GWT brings tools that simplify the project creation step for Eclipse.

Creating a project

So let's start coding. First of all, we're going to create a project and an application. To do that, we'll use two utilities, applicationCreator and projectCreator. It's
necessary to create a directory where the project files will be placed. Add the GWT directory to the environment variable PATH, to make project creation easier
and from project's directory, run the command

projectCreator -eclipse TutorialGWT

to create the project, and then, run the command

applicatoinCreator -eclipse TutorialGWT br.com.javamagazine.client.TutorialGWT

The basic Eclipse project structure will be created, with GWT libraries references already configured. At Eclipse, just import the created project (Menu
File>Import>Existing projects into workspace), and the configurations will be automatically set up. The project structure should be similar to the presented below:

1 of 5 3/23/2008 14:17
Google Web Toolkit Tutorial - douglasjose.com http://douglasjose.com/tech/tutorials/gwt.html

Implementing the sample problem

In this tutorial, the sample problem that we will solve is the creation of an incremental find. The find is incremental because the filter criteria is applied as the
characters are typed. Firefox users are familiar with this kind of search (just press Control + F to open the Firefox incremental find panel).
This tutorial will use a basic text field as filter. As soon as the text field is filled, a list will show only the elements that matches the typed filter. Observe that the
used components (text box, list) are common HTML form fields, and there are no web server requests in this sample (although it will probably happen when
solving real problems).
Open the TutorialGWT.html file and change it as the code below.

1:<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


2:<html>
3: <head>
4: <title>
5: Tutorial GWT
6: </title>
7:<style type="text/css">
8:body,td,a,div,.p{font-family:arial,sans-serif}
9:div,td{color:#000000}
10:a:link,.w,.w a:link{color:#0000cc}
11:a:visited{color:#551a8b}
12:a:active{color:#ff0000}
13:.list {width: 100%;}
14:</style>
15: <meta name='gwt:module' content=
16: 'br.com.javamagazine.TutorialGWT'>
17: </head>
18: <body>
19: <script language="javascript" src="gwt.js" type=
20: "text/javascript">
21:</script>
22:<!-- OPTIONAL: include this if you want history support -->
23: <iframe id="__gwt_historyFrame" style=
24: "width:0;height:0;border:0" name=
25: "__gwt_historyFrame"></iframe>
26: <h1>
27: Tutorial GWT
28: </h1>
29: <div id="input" align="center"></div>
30: <table align="center">
31: <tr>
32: <td>
33: <table align="center" width="400">
34: <tr>
35: <td id="label"></td>
36: <td id="text" width="100%"></td>
37: </tr>
38: <tr>
39: <td id="list" colspan="2"></td>
40: </tr>
41: <tr>
42: <td id="removeContact" align="center" colspan="2">
43: </td>
44: </tr>
45: </table>
46: </td>
47: <td>
48: <table align="center">
49: <tr>
50: <td>
51: First name :
52: </td>
53: <td id="firstName"></td>
54: </tr>
55: <tr>
56: <td>

2 of 5 3/23/2008 14:17
Google Web Toolkit Tutorial - douglasjose.com http://douglasjose.com/tech/tutorials/gwt.html

57: Last name :


58: </td>
59: <td id="lastName"></td>
60: </tr>
61: <tr>
62: <td>
63: E-mail:
64: </td>
65: <td id="email"></td>
66: </tr>
67: <tr>
68: <td colspan="2">
69: <div id="insertContact" align="center"></div>
70: </td>
71: </tr>
72: </table>
73: </td>
74: </tr>
75: </table>
76: </body>
77:</html>
78:

You will notice that we made a few changes from the original file generated by GWT. Eight IDs are defined; they represent the places where the components will
be shown. The CSS style .list is defined to place the list properly.
Next step is to edit TutorialGWT class that will describe the incremental find behavior. In this sample, a simple contacts catalog was created, where is possible to
store a contact first name, last name and e-mail address, and also remove any previously created contact. The incremental find is useful to filter all previously
added contacts. In this class are defined some auxiliary methods to fill the list, to search the list using a filter and to check if a String is contained in other String
(contains method).
This method deserves a special explanation. Although Java API already defines the method contains for java.lang.String class, we need to redefine it, because
GWT compiler is not able to translate this method to JavaScript code.
The final code for TutorialGWT class can be found here

1:package br.com.javamagazine.client;
2:
3:import java.util.*;
4:import com.google.gwt.core.client.EntryPoint;
5:import com.google.gwt.user.client.ui.*;
6:
7:/**
8: * Entry point classes define <code>onModuleLoad()</code>.
9: *
10: * @author Douglas
11: * @created October 15, 2006
12: */
13:public class TutorialGWT implements EntryPoint {
14:
15: private List items = new ArrayList();
16: //Contém os contatos cadastrados
17:
18:
19: /**
20: * Description of the Method
21: */
22: public void onModuleLoad() {
23:
24: final Label label = new Label("Filtro:");
25: final ListBox list = new ListBox();
26: final TextBox filter = new TextBox();
27: final TextBox firstName = new TextBox();
28: final TextBox lastName = new TextBox();
29: final TextBox email = new TextBox();
30: final Button insertContact = new Button("Adicionar");
31: final Button deleteContact = new Button("Remover");
32:
33:// Listener que trata cada caractere digitado no campo de filtro
34: filter.addKeyboardListener(
35: new KeyboardListenerAdapter() {
36: public void onKeyUp(Widget sender, char keyCode, int modifiers) {
37: filterList(list, filter.getText());
38: }
39: });
40:
41:// Listener que trata o clique no botão 'Adicionar'
42: insertContact.addClickListener(
43: new ClickListener() {
44: public void onClick(Widget sender) {
45: insertContact(list, firstName.getText(), lastName.getText(), email.getText(),
46: filter.getText());
47: firstName.setText("");
48: lastName.setText("");
49: email.setText("");
50: }

3 of 5 3/23/2008 14:17
Google Web Toolkit Tutorial - douglasjose.com http://douglasjose.com/tech/tutorials/gwt.html

51: });
52:
53:// Listener que trata o clique no botão 'Remover'
54: deleteContact.addClickListener(
55: new ClickListener() {
56: public void onClick(Widget sender) {
57: int i = list.getSelectedIndex();
58: items.remove(i);
59: filterList(list, filter.getText());
60: }
61: });
62:
63: list.setVisibleItemCount(5);
64: // Numero de itens exibidos
65: list.setStyleName("list");
66:
67: RootPanel.get("label").add(label);
68: RootPanel.get("text").add(filter);
69: RootPanel.get("list").add(list);
70: RootPanel.get("firstName").add(firstName);
71: RootPanel.get("lastName").add(lastName);
72: RootPanel.get("email").add(email);
73: RootPanel.get("insertContact").add(insertContact);
74: RootPanel.get("removeContact").add(deleteContact);
75: }
76:
77:
78: /**
79: * Description of the Method
80: *
81: * @param list Description of the Parameter
82: * @param firstName Description of the Parameter
83: * @param lastName Description of the Parameter
84: * @param email Description of the Parameter
85: * @param filter Description of the Parameter
86: */
87: private void insertContact(ListBox list, String firstName, String lastName, String email,
88: String filter) {
89: String newContact = lastName + ", " + firstName + " (" + email + ")";
90: list.addItem(newContact);
91: items.add(newContact);
92: filterList(list, filter);
93: }
94:
95:
96: /**
97: * Description of the Method
98: *
99: * @param list Description of the Parameter
100: * @param filter Description of the Parameter
101: */
102: private void filterList(ListBox list, String filter) {
103: list.clear();
104: for (int i = 0; i < items.size(); i++) {
105: String item = (String) items.get(i);
106: if (contains(item.toLowerCase(), filter.toLowerCase())) {
107: list.addItem(item);
108: }
109: }
110: }
111:
112:
113: /**
114: * Description of the Method
115: *
116: * @param original Description of the Parameter
117: * @param filter Description of the Parameter
118: * @return Description of the Return Value
119: */
120: private boolean contains(String original, String filter) {
121: if (filter.length() == 0) {
122: return true;
123: }
124: if (filter.length() > original.length()) {
125: return false;
126: }
127: for (int i = 0; i < original.length() - filter.length() + 1; i++) {
128: if (original.charAt(i) == filter.charAt(0)) {
129: boolean matches = true;
130: for (int j = 0; j < filter.length(); j++) {
131: if (original.charAt(i + j) != filter.charAt(j)) {
132: matches = false;

4 of 5 3/23/2008 14:17
Google Web Toolkit Tutorial - douglasjose.com http://douglasjose.com/tech/tutorials/gwt.html

133: break;
134: }
135: }
136: if (matches) {
137: return true;
138: }
139: }
140: }
141: return false;
142: }
143:}
144:
145:

Running and compiling

After editing the Java and HTML files, click the Run button and you will see the local browser running. Two windows will be shown, one is the application log, and
the other is the browser showing our application.

Notice that until now, no JavaScript code was generated. To do that, we'll use GWT compiler. Just run the TutorialGWT-complie.cmd file, that's placed at project
root directory. The directory www/br.com.javamagazine.TutorialGWT will be created, with the target HTML files. Now your application can be viewed from any
JavaScript-enabled browser.

Conclusion

GWT presents itself as a well written and robust framework. In its distribution package all necessary tools are included, and its IDE integration (currently only
Eclipse is supported) is quite simple.
And the new programming paradigm presented by this framework shows that Google, besides being present in about all internet users everyday tasks, now
presents surprisingly and innovative solutions to web based application developers too.

Bookmarks

Google Web Toolkit


http://code.google.com/webtoolkit

Eclipse WebTools
http://www.eclipse.org/webtools

5 of 5 3/23/2008 14:17

You might also like